package com.baimo.controller;

import com.baimo.pojo.Comment;
import com.baimo.pojo.User;
import com.baimo.service.BlogService;
import com.baimo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @author 白墨
 * @ClassName CommentController.java
 * @Description TODO
 * @createTime 2021/4/24 0:48:19
 */
@Controller
public class CommentController
{
    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("blog", blogService.getBlog(blogId));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        User user = (User) session.getAttribute("user");
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        } else {
            comment.setAvatar(avatar);
        }
        Integer integer = commentService.saveComment(comment);
        if (integer>0){
            session.setAttribute("msg","发布成功");
        }else {
            session.setAttribute("msg","发布失败");
        }
        return "redirect:/comments/" + blogId;
    }

    @PostMapping("/admin/comment/delete")
    public String deleteComment(Comment comment, HttpSession session) {
        Integer integer = commentService.deleteComment(comment);
        if (integer>0){
            session.setAttribute("msg","删除成功");
        }else {
            session.setAttribute("msg","删除失败");
        }
        return "redirect:/comments/" + comment.getBlog().getId();
    }
}
